<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>敏感词替换</div>
    <div class="word">,,bad,idfgbadbodfbbadwordgonsdlfbad,dbanbadword</div>
  </body>
  <script>
    var badwords = ["bad", "badword"]; //敏感词词库

    var wordDom = document.querySelector(".word");
    var text = wordDom.innerText;

    console.log(text.includes("bad"));//有就返回true，没有返回false
    for (var i = 0; i < badwords.length; i++) {
      while (text.indexOf(badwords[i]) != -1) {//从字符串中找出子字符串的位置(index);当返回-1时，找不到这个子字符串
        text = text.replace(badwords[i], "********");//replace只能匹配第一个，最前面那个
        wordDom.innerText = text;
      }
    }
  </script>
</html>
